//
//  COUserInfo.swift
//  CocoProject
//
//  Created by Ruthless on 2023/8/11.
//

import HandyJSON

@objcMembers
class COUserInfo: NSObject, HandyJSON, NSSecureCoding {
    var id: Int = 0
    var userId = 0
    var nickName: String = ""
    var sculpture: String = ""
    var age: Int = 0
    var level: String = ""
    var token: String = ""
    var food: String = ""
    var email = ""
        
    required override init() {
        
    }
    
    // MARK: - 解档
    required init?(coder: NSCoder) {
        super.init()
        
        for name in getAllPropertys() {
            let value = coder.decodeObject(forKey: name)
            setValue(value, forKeyPath: name)
        }
    }
    
    // MARK: - 归档
    func encode(with coder: NSCoder) {
        for name in getAllPropertys() {
            let value = self.value(forKey: name)
            coder.encode(value, forKey: name)
        }
    }
    
    static var supportsSecureCoding: Bool {
        return true
    }
}

extension COUserInfo {
    ///  获取所有属性
    func getAllPropertys() -> [String] {
        var count: UInt32 = 0
        let properties = class_copyPropertyList(self.classForCoder, &count)
        var propertyNames: [String] = []
        for i in 0..<Int(count) {
            if let property = properties?[i] {
                let name = property_getName(property)
                let strName = String(cString: name)
                propertyNames.append(strName)
            }
        }
        free(properties)
        return propertyNames
    }
}
